<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="800"
    :body-style="{
      height: '400px !important',
    }"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <div class="sub-title">基本信息</div>
    <BasicForm @register="registerForm">
      <template #imgUpload="{ model }">
        <Upload v-model:value="model.filePath" listType="picture" />
      </template>
    </BasicForm>
    <div class="config-title">
      <span class="font-semibold">联系人</span>
      <span class="add-span" @click="addConfig">+ 增加</span>
    </div>
    <a-radio-group v-model:value="defaultIndex" style="width: 100%">
      <a-form
        ref="formRef"
        :model="personList"
        name="personList"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        autocomplete="off"
      >
        <template v-for="(item, index) in personList.list" :key="index">
          <a-row style="margin: 0 0 20px 10px">
            <a-col :span="20" style="color: #999">联系人{{ index + 1 }}</a-col>
            <a-col :span="4" align="right">
              <a-radio :value="index">默认</a-radio>
              <span @click="deleteConfig(index)" class="delete-span">删除</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item
                label="姓名"
                :name="['list', index, 'name']"
                :rules="{ required: true, message: '请输入姓名', trigger: 'change' }"
              >
                <a-input v-model:value="item.name" placeholder="请输入姓名" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="电话" :name="['list', index, 'phone']">
                <a-input v-model:value="item.phone" placeholder="请输入电话" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="职位" :name="['list', index, 'post']">
                <a-input v-model:value="item.post" placeholder="请输入职位" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门" :name="['list', index, 'dept']">
                <a-input v-model:value="item.dept" placeholder="请输入部门" />
              </a-form-item>
            </a-col>
          </a-row>
        </template>
      </a-form>
    </a-radio-group>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addCustomer, updateCustomer, getCustomerInfo } from '/@/api/erp/customer/list';
  const { t } = useI18n();

  const FormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '客户名称',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入客户名称',
      },
    },
    {
      field: 'typeId',
      label: '客户类型',
      component: 'DicSelect',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择客户类型',
        itemId: '1679007059387240450',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'industry',
      label: '所在行业',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入所在行业',
      },
    },
    {
      field: 'sourceId',
      label: '来源',
      component: 'DicSelect',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择来源',
        itemId: '1679008505423876097',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'scaleId',
      label: '规模',
      component: 'DicSelect',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择规模',
        itemId: '1679009315172012034',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'natureId',
      label: '公司性质',
      component: 'DicSelect',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择公司性质',
        itemId: '1679010661178691585',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'address',
      label: '地址',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入地址',
      },
    },
    {
      field: 'filePath',
      label: '图片上传',
      component: 'Upload',
      slot: 'imgUpload',
      colProps: { span: 24 },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const state = ref();
  const defaultIndex = ref(0);
  const formRef = ref();
  const personList = ref<any>({
    list: [
      {
        isDefault: false,
        dept: '',
        name: '',
        phone: '',
        post: '',
      },
    ],
  });

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    state.value = data?.state;
    defaultIndex.value = 0;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getCustomerInfo(data.id);
      setFieldsValue({ ...record });
      personList.value.list = [...record.caseErpCustomerContacts];
      personList.value.list.some((x, idx) => {
        if (x.isDefault) {
          defaultIndex.value = idx;
          return true;
        }
        return false;
      });
    } else {
      personList.value = {
        list: [
          {
            isDefault: false,
            dept: '',
            name: '',
            phone: '',
            post: '',
          },
        ],
      };
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增客户' : '编辑客户'));

  const addConfig = () => {
    personList.value.list.push({ isDefault: false, dept: '', name: '', phone: '', post: '' });
  };

  const deleteConfig = (index) => {
    personList.value.list.splice(index, 1);
  };

  async function handleSubmit() {
    try {
      const values = await validate();
      await formRef.value.validate();

      if (personList.value.list.length) {
        personList.value.list.map((x, idx) => (x.isDefault = idx === defaultIndex.value ? 1 : 0));
      }

      const info = {
        ...values,
        state: state.value,
        addCaseErpCustomerContactsDtoList: personList.value.list,
      };
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addCustomer(info);
        notification.success({
          message: '新增客户',
          description: t('成功'),
        });
      } else {
        info.id = rowId.value;
        await updateCustomer(info);
        notification.success({
          message: '编辑客户',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  .sub-title {
    font-weight: 700;
    margin: 0 18px 18px;
  }

  .config-title {
    display: flex;
    justify-content: space-between;
    margin: 18px;
    font-weight: 700;

    .add-span {
      color: #5e95ff;
      cursor: pointer;
    }
  }

  .delete-span {
    color: #ff8080;
    cursor: pointer;
  }
</style>
